<template>
  <div>
    <a-space direction="vertical" fill>
      <a-card>
        <div class="params">
          <div class="item">
            <span>oaid:</span> <a-input v-model="params.oaid"></a-input>
          </div>
          <!-- 添加日期范围筛选 -->
          <div class="item">
            <span>日期范围:</span>
            <a-range-picker
              v-model="dateRange"
              style="flex: 1"
              @change="onDateChange"
              value-format="YYYY-MM-DD" />
          </div>
          <div class="search-btn">
            <a-button type="primary" @click="getLogListData">搜索</a-button>
          </div>
        </div>
      </a-card>
      <a-card>
        <span
          >这里的浏览量只是 app 进入的次数 并且没有记录 每次进入的时间
        </span>
        <div style="margin:6px 0">
          <span>所有浏览量只是平台进入量的总和 </span>
        </div>
        <a-space>
          <a-tag>总进入量:{{ totalsData.enterTotal }}</a-tag>
          <a-tag>总追踪成功:{{ totalsData.track1 }}</a-tag>
          <a-tag>总追踪失败:{{ totalsData.track0 }}</a-tag>
        </a-space>
      </a-card>

      <div class="platform-card">
        <a-card
          class="stats-card"
          v-for="item in statsList"
          :key="item.platform">
          <template #title>
            <div class="card-title">
              <icon-desktop />
              {{ getPlatformName(item.platform) }}
            </div>
          </template>

          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-label">进入总数</div>
              <div class="stat-value">{{ item.enterTotal }}</div>
            </div>
            <!-- <div class="stat-item">
              <div class="stat-label">记录数</div>
              <div class="stat-value">{{ item.records }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">平均进入</div>
              <div class="stat-value">
                {{ calculateAverage(item.enterTotal, item.records) }}
              </div>
            </div> -->
          </div>
        </a-card>
      </div>

      <!-- 获取日志列表 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :pagination="{
          current: params.page,
          pageSize: params.page_size,
          total: total,
          onChange: onPageChange
        }">
        <!-- :scroll="{
        x: 2000
      }" -->
        <template #oaid="{ record }">
          <a-space direction="vertical">
            <div>
              <a-tooltip :content="record.oaid">
                <a-button>oaid{{ record.oaid ? "" : "/无" }}</a-button>
              </a-tooltip>
            </div>
            <a-button type="primary" @click="seeTrackCallback(record)">
              查看监测地址
            </a-button>
          </a-space>
        </template>
        <!-- <template #location="{ record }">
        <pre style=""
          >{{ genLocation(record) }}
        </pre>
      </template> -->
        <template #track="{ record }">
          <div class="status" :class="[`track-${record.track}`]">
            {{ record.track == 1 ? "成功" : "失败" }}
          </div>
        </template>
        <template #error="{ record }">
          <a-button @click="() => onErrorSee(record)">查看</a-button>
        </template>
        <template #data="{ record }">
          <a-button @click="() => onDataSee(record)">查看</a-button>
        </template>
      </a-table>
    </a-space>
    <a-drawer
      :width="340"
      :visible="visible"
      :footer="false"
      @cancel="visible = false"
      @close="visible = false">
      <template #title> Title </template>
      <div>
        <div v-for="(item, key) in drawerList">
          <div>
            <span>进入:{{ item.enter }}</span>
          </div>
          <template v-if="item.num">
            <div>banner:{{ item.num.banner }}</div>
            <div>interstitial:{{ item.num.interstitial }}</div>
            <div>video:{{ item.num.video }}</div>
          </template>
          <div>时间:{{ item.time }}</div>
          <hr />
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, h } from "vue";
import { tableHeader } from "./data.js";
import { getLogList, getTrackCallback, getPlatformView } from "./api.js";
import { Message, Modal, Drawer } from "@arco-design/web-vue";
import ErrorCom from "./error-com.vue";
import See from "./see.vue";

const map = {
  video: "视频",
  banner: "横幅",
  interstitial: "插屏"
};
const plMap = {
  oppo: "oppo",
  vivo: "vivo",
  xiaomi: "小米",
  huawei: "华为",
  meizu: "魅族",
  samsung: "三星",
  hw_honor: "华为荣耀",
  xiaomi_redmi: "小米红米",
  honor: "荣耀",
  oneplus: "一加"
};
const getPlatformName = (platform) => {
  return plMap[platform] || platform;
};
// 计算平均值
const calculateAverage = (enterTotal, records) => {
  if (!records) return "0.0";
  return (enterTotal / records).toFixed(1);
};

// 格式化数字显示
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

const visible = ref(false);
const drawerList = ref([]);
const dateRange = ref([]);
const columns = tableHeader;
const tableData = ref([]);
const totalsData = ref({
  enterTotal: 0,
  track1: 0,
  track0: 0
});
const params = reactive({
  page: 1,
  page_size: 10,
  oaid: ""
});
const statsList = ref([]);
const total = ref(1);

function onDataSee(e) {
  // const d = JSON.parse(e.data || '{"fake":{}}');
  drawerList.value = genData(e);
  visible.value = true;
}

// 添加日期变更处理函数
function onDateChange(dates) {
  if (dates && dates.length === 2) {
    params.start_date = dates[0];
    params.end_date = dates[1];
  } else {
    delete params.start_date;
    delete params.end_date;
  }
}

function onErrorSee(e) {
  // const d = JSON.parse(e.error || '{"info":[]}');
  // drawerList.value = genErrorInfo(e);
  // visible.value = true;
  Drawer.open({
    title: "错误信息",
    width: 400,
    footer: false,
    content: () =>
      h(ErrorCom, {
        list: genErrorInfo(e)
      })
  });
}

function onPageChange(page) {
  params.page = page;
  getLogListData();
}

function genData(e) {
  const d = JSON.parse(e.data || '{"fake":{}}');
  // console.log(d);

  // d.fake.length = Object.keys(d.fake).length;

  return d.fake;
  // return JSON.stringify(JSON.parse(d), null, 2);
}

function genErrorInfo(e) {
  const d = JSON.parse(e.error || '{"info":[]}');
  // console.log(d);

  return d.info.map((e) => {
    let result = e;
    try {
      result = JSON.parse(e);
    } catch (error) {}

    // return JSON.stringify(result, null, 2);
    return result;
  });
}

function genLocation(e) {
  const d = JSON.parse(e.location || "{}");
  return d;
  // return JSON.stringify(JSON.parse(d), null, 2);
}
function getLogListData() {
  getLogList(params).then((resp) => {
    // console.log(resp);
    tableData.value = resp.data || [];
    total.value = resp.total || 1;
    // totalsData.value = resp.totals || {};
  });

  getPlatformView(params).then((resp) => {
    console.log(resp);
    statsList.value = resp.stats || [];
    totalsData.value = resp.totals || {}
  });
}
// 查看是否有追踪检测地址
function seeTrackCallback(e) {
  const oaid = e.oaid;
  console.log(oaid);
  getTrackCallback({
    // oaid: "83D18FF15043471EAB1B572ED4D4CC3E8c5df35eb9d355b93c1d1e5fedaa6dc2"
    oaid
  })
    .then((data) => {
      console.log(data);
      Modal.info({
        title: "监测地址",
        width: 1000,
        content: () =>
          h(See, {
            url: data.callbackurl,
            time: data.create_time
          })
      });
    })
    .catch((err) => {
      console.log(err);
      Message.error(err);
    });
}

(function onMounted() {
  getLogListData();
})();
</script>

<style lang="less" scoped>
.params {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  grid-gap: 10px;
  .item {
    display: flex;
    align-items: center;
    span {
      width: 80px;
    }
    .arco-input-wrapper {
      flex: 1;
    }
  }
}
.status {
  &.track-1 {
    color: green;
  }
  &.track-0 {
    color: red;
  }
}
//
.platform-card {
  display: flex;
  .stats-card {
    flex: 1;
    &:not(:last-child) {
      margin-right: 10px;
    }
  }
}
.stat-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
